<template>
  <el-dialog
    top="30px"
    append-to-body
    title="准入审批"
    width="800px"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :rules="rules" ref="form" label-width="110px" :model="editData">
      <el-form-item label="机构名称:">
        <el-input v-model="formData.agency_name" class="form-control-ml" disabled></el-input>
      </el-form-item>
      <el-form-item label="授信金额:" prop="credit_amount" v-if="is28Business">
        <el-input
          v-model="editData.credit_amount"
          class="form-control-ml"
          v-input-number="{ min: 0, fixed: 2 }"
          placeholder="请输入授信金额"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="贷款利率" v-if="!is28Business" prop="load_rate">
        <el-input
          v-model="editData.load_rate"
          class="form-control-ml"
          placeholder="请输入贷款利率"
          v-input-number="{ min: 0, fixed: 2, max: 100 }"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="风险分担比列" v-if="!is28Business" prop="risk_rate">
        <el-input
          v-model="editData.risk_rate"
          class="form-control-ml"
          placeholder="请输入风险分担比列"
          v-input-number="{ min: 0, fixed: 2, max: 100 }"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>

      <el-form-item label="业务规模占比(10-300万)" v-if="!is28Business" prop="bus_scale_rate">
        <el-input
          v-model="editData.bus_scale_rate"
          class="form-control-ml"
          placeholder="请输入业务规模占比(10-300万)"
          v-input-number="{ min: 0, fixed: 2, max: 100 }"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>

      <el-form-item label="代偿比例" v-if="!is28Business" prop="comps_rate">
        <el-input
          v-model="editData.comps_rate"
          class="form-control-ml"
          placeholder="请输入代偿比例"
          v-input-number="{ min: 0, fixed: 2, max: 100 }"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>

      <el-form-item label="保证合同号" v-if="!is28Business" prop="gua_contract">
        <el-input
          v-model="editData.gua_contract"
          class="form-control-ml"
          placeholder="请输入保证合同号"
        ></el-input>
      </el-form-item>
      <el-form-item label="合作金额" v-if="!is28Business" prop="coo_amount">
        <el-input
          v-model="editData.coo_amount"
          class="form-control-ml"
          placeholder="请输入合作金额"
          v-input-number="{ min: 0, fixed: 2 }"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="合作开始时间:" prop="cooperate_date_start">
        <el-date-picker
          v-model="editData.cooperate_date_start"
          class="form-control-ml"
          placeholder="合作开始时间"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="合作结束时间:" prop="cooperate_date_end">
        <el-date-picker
          v-model="editData.cooperate_date_end"
          class="form-control-ml"
          placeholder="合作结束时间"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="资本金:">
        <el-input
          v-model="editData.margin_amount"
          class="form-control-ml"
          v-input-number="{ min: 0, fixed: 2 }"
          placeholder="请输入资本金"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="业务受理机构:">
        <div class="bank-cascader__tags form-control-ml" @click="handleSelect">
          <span v-if="!presentNodes.length" class="bank-cascader__hint">请选择合作机构：</span>
          <el-tag v-for="node in presentNodes" :key="node.uid" type="info" disable-transitions>
            <span>{{ node.label }}</span>
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item label="附件上传:">
        <upload-oss
          multiple
          accept="image/*"
          listType="picture-card"
          ref="upload"
          :file-list="attachFileList"
          :limit="10"
          :on-complete="handleImagesComplete"
        ></upload-oss>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-long" :loading="buttonLoading" @click="handleSubmit">
          准入
        </el-button>
        <el-button type="danger" class="btn-long" :loading="buttonLoading" @click="handleReject">
          拒绝
        </el-button>
      </el-form-item>
    </el-form>
    <select-access-bank-dialog
      :top-value="formData.agency_id"
      v-model="branchIds"
      @change="setNodes"
      :visible.sync="accessVisible"
    >
      <template v-slot:footer>
        <div class="text-center mt-2">
          <el-button @click="closeSelect" type="primary" class="btn-long">保存</el-button>
          <el-button @click="closeSelect" class="btn-long">取消</el-button>
        </div>
      </template>
    </select-access-bank-dialog>
  </el-dialog>
</template>

<script>
import SelectAccessBankDialog from '@/credit/components/select/SelectAccessBankDialog'
export default {
  components: {
    SelectAccessBankDialog,
  },
  props: {
    visible: Boolean,
    formData: Object,
    type: String,
  },
  data() {
    return {
      editData: {},
      rules: {
        credit_amount: { required: true, message: '请输入授信金额', trigger: 'blur' },
        cooperate_date_start: { required: true, message: '请选择合作开始时间', trigger: 'change' },
        cooperate_date_end: { required: true, message: '请选择合作结束时间', trigger: 'change' },
        // margin_amount: { required: true, message: '请输入资本金', trigger: 'blur' },
        load_rate: { required: true, message: '请输入贷款利率', trigger: 'blur' },
        risk_rate: { required: true, message: '请输入风险分担比例', trigger: 'blur' },
        bus_scale_rate: {
          required: true,
          message: '请输入业务规模占比(10-300万)',
          trigger: 'blur',
        },
        comps_rate: { required: true, message: '请输入代偿比例', trigger: 'blur' },
        gua_contract: { required: true, message: '请输入保证合同号', trigger: 'blur' },
        coo_amount: { required: true, message: '请输入合作金额', trigger: 'blur' },
      },
      attachFileList: [],
      branchIds: [],
      presentNodes: [],
      accessVisible: false,
      approvalTable: 'credit_agency_access',
      buttonLoading: false,
    }
  },

  computed: {
    queryId() {
      return this.formData.credit_agency_access_id || ''
    },
    is28Business() {
      return +this.type === 1
    },
  },

  watch: {
    formData: {
      handler: function () {
        this.editData = { ...this.formData }
        if (!this.is28Business) {
          this.editData.load_rate = this.formData.load_rate || 8.5
        }
        this.getBranch()
      },
      deep: true,
      immediate: true,
    },
  },

  created() {},
  methods: {
    getBranch() {
      this.presentNodes = []
      this.branchIds = []
      if (!this.queryId) {
        return
      }
      const params = { 'credit_agency_access_id.eq': this.queryId }
      this.$api
        .getData(this.$serviceName, 'credit_agency_access_detail_view', params, {
          agency_name: 'asc',
        })
        .then(res => {
          const data = (res && res.data) || []
          this.branchIds = []
          data.forEach(item => {
            this.presentNodes.push({
              label: item.agency_name,
              value: item.agency_id,
              credit_agency_access_id: item.credit_agency_access_id,
            })
            this.branchIds.push(item.agency_id)
          })
        })
    },
    saveData(attachment) {
      let keys = []
      if (this.is28Business) {
        keys = [
          'access_agency_id',
          'service_id',
          'credit_agency_access_id',
          'access_status',
          'margin_amount',
          'credit_amount',
          'cooperate_date_end',
          'cooperate_date_start',
        ]
      } else {
        keys = [
          'access_agency_id',
          'service_id',
          'credit_agency_access_id',
          'access_status',
          'margin_amount',
          'load_rate',
          'risk_rate',
          'bus_scale_rate',
          'comps_rate',
          'gua_contract',
          'coo_amount',
          'cooperate_date_end',
          'cooperate_date_start',
        ]
      }

      const data = {}
      data.attachment = attachment
      keys.forEach(key => {
        data[key] = this.editData[key]
      })
      const slaveData = []
      this.presentNodes.forEach(item => {
        slaveData.push({
          access_agency_name: item.label,
          access_agency_id: item.value,
          credit_agency_access_id: this.editData.credit_agency_access_id,
        })
      })
      const formData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: 'credit_agency_access',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'credit_agency_access_detail',
      }
      this.buttonLoading = true
      this.$api
        .relatedUpdate(this.$serviceName, formData)
        .then(() => {
          this.$message.success('操作成功')
          this.branchIds = []
          this.presentNodes = []
          this.beforeClose()
          this.$emit('success', true)
        })
        .catch(() => {
          this.$message.error('操作失败')
        })
        .finally(() => {
          this.buttonLoading = false
        })
    },
    handleSubmit() {
      this.editData.access_status = 1
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$refs.upload.submit()
        } else {
          this.$message.error('输入错误，请重新填写!')
        }
      })
    },
    handleReject() {
      this.$msgbox({
        title: '提示',
        message: `拒绝准入: ${this.formData.agency_name}?`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonText = '操作中...'
            instance.confirmButtonLoading = true

            this.editData.access_status = 2
            this.$refs.upload.submit()

            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            done()
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
    handleSelect() {
      this.accessVisible = true
    },
    closeSelect() {
      this.accessVisible = false
    },
    setNodes(val, nodes) {
      this.presentNodes = nodes
    },
    handleImagesComplete(images = []) {
      const imageStr = images.length ? `["${images.map(item => item.url).join('","')}"]` : ''
      this.saveData(imageStr)
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.bank-cascader__tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  border-radius: 4px;
  border: 1px solid $border-color;
  padding: 3px 40px 3px 10px;
  margin-bottom: 6px;
  min-height: 38px;
  position: relative;
  cursor: pointer;
  .bank-cascader__hint {
    color: $gray-600;
    line-height: 32px;
  }
  .el-tag {
    display: inline-block;
    align-items: center;
    margin: 2px 0 2px 6px;
    text-overflow: ellipsis;
    background: #f0f2f5;
  }
}
</style>
